package com.gxa.saas.portal.controller.btopfore;


import com.fasterxml.uuid.impl.UUIDUtil;
import com.gxa.saas.core.utils.JwtUtil;
import com.gxa.saas.portal.entity.vo.wylvo.GoodsVo;
import com.gxa.saas.portal.mapper.hhy.SelectShopIdMapper;
import com.gxa.saas.portal.service.AddJestService;
import com.gxa.saas.portal.service.WGoodsService;
import com.gxa.saas.portal.util.ImageUpload;
import com.gxa.saas.portal.util.TencentUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotEmpty;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/wgoods")
public class GoodsManagement {

    @Resource
    private WGoodsService wGoodsService;

    @Autowired
    private TencentUtil tencentUtil;

    @Resource
    private AddJestService addJestService;



    @ApiOperation("店铺管理显示数据获取")
    @GetMapping("/goodsData")
    public Map goodsData(HttpServletRequest request){
        //根据登录账号获取商铺id

        String sid=JwtUtil.getUsername(request.getAttribute("token1").toString());
        Integer shopId = wGoodsService.selectShopId(sid);
        List<GoodsVo> list = wGoodsService.goodsData(shopId);

        if(list.size()==0){
            List<GoodsVo> list1 = new ArrayList<>();
            GoodsVo goodsVo = new GoodsVo();
            list1.add(goodsVo);
            Map map = new HashMap();
            map.put("msg","暂无信息没有商品");
            map.put("code",200);
            map.put("data",list1);
            return map;
        }

//        List<GoodsVo> list = new ArrayList<>();
//        GoodsVo goodsVo = new GoodsVo();
//        list.add(goodsVo);
        Map map = new HashMap();
        map.put("msg","查询成功");
        map.put("code",200);
        map.put("data",list);
        return map;
    }
    @ApiOperation("切换分类管理")
    @GetMapping("/changeCategory")
   public Map changeCategory(HttpServletRequest request,@NotEmpty(message = "产品类别")String  category){
        //根据登录账号获取商铺id
        String sid=JwtUtil.getUsername(request.getAttribute("token1").toString());
        Integer shopId = wGoodsService.selectShopId(sid);


        List<GoodsVo> list = wGoodsService.changeCategory(shopId, category);

        if(list.size()==0){
            List<GoodsVo> list1 = new ArrayList<>();
            GoodsVo goodsVo = new GoodsVo();
            list1.add(goodsVo);
            Map map = new HashMap();
            map.put("msg","该品类没有商品");
            map.put("code",200);
            map.put("data",list1);
            return map;
        }

        System.out.println(category);
//        List<GoodsVo> list = new ArrayList<>();
//        GoodsVo goodsVo = new GoodsVo();
//        list.add(goodsVo);
        Map map = new HashMap();
        map.put("msg","切换成功");
        map.put("code",200);
        map.put("data",list);
        return map;
   }
    @ApiOperation("商品查询")
    @GetMapping("/selectgoods")
    public Map selectGoods(HttpServletRequest request,String  goods){

        //根据登录账号获取商铺id

        String sid=JwtUtil.getUsername(request.getAttribute("token1").toString());
        Integer shopId = wGoodsService.selectShopId(sid);

        List<GoodsVo> list = wGoodsService.selectGoods(shopId, goods);

        if(list.size()==0){
            List<GoodsVo> list1 = new ArrayList<>();
            GoodsVo goodsVo = new GoodsVo();
            list1.add(goodsVo);
            Map map = new HashMap();
            map.put("msg","没有该商品");
            map.put("code",200);
            map.put("data",list1);
            return map;
        }


        System.out.println(goods);
//        List<GoodsVo> list = new ArrayList<>();
//        GoodsVo goodsVo = new GoodsVo();
//        list.add(goodsVo);
        Map map = new HashMap();
        map.put("msg","查询成功");
        map.put("code",200);
        map.put("data",list);
        return map;
    }


    @ApiOperation("商品上下架")
    @GetMapping("/updatestate")
    @Transactional
    public Map updateState(HttpServletRequest request,@NotEmpty(message = "商品id")Integer  id,@NotEmpty(message = "商品状态")Integer status){

        //根据登录账号获取商铺id
        String sid=JwtUtil.getUsername(request.getAttribute("token1").toString());
        Integer shopId = wGoodsService.selectShopId(sid);

        if(status==1){
            wGoodsService.updateState(shopId,id,status);
            String prid = wGoodsService.selectPrid(id);
            this.addJestService.newAdd(prid);
            Map map = new HashMap();
            map.put("msg","上架成功");
            map.put("code",200);
            return map;
        }
        wGoodsService.updateStateDown(shopId,id,status);
        String prid = wGoodsService.selectPrid(id);
        addJestService.delete(prid);
        System.out.println(id);
        Map map = new HashMap();
        map.put("msg","下架成功");
        map.put("code",200);
        return map;
    }

    @ApiOperation("商品编辑")
    @PostMapping("/updatgoods")
    @Transactional
    //前端使用表单提交
    public Map updateGoods(@ModelAttribute @Validated GoodsVo goods){

        String prPrice = goods.getPrPrice();
        BigDecimal price = BigDecimal.valueOf(Long.parseLong(prPrice));
        goods.setPrPric(price);

        System.out.println(goods);

        wGoodsService.updateGoods(goods);

        MultipartFile picture = goods.getPicture();

        String pic=null;
        //图片地址
        try {
            pic = ImageUpload.upload(picture);

        } catch (IOException e) {
            e.printStackTrace();
        }
        //修改图片
        wGoodsService.updatePic(pic,goods.getId());
        System.out.println(goods);
        Map map = new HashMap();
        map.put("msg","商品编辑成功");
        map.put("code",200);
        return map;
    }


    @ApiOperation("创建商品前的类别查询")
    @PostMapping("/selectCategory")
    public Map selectCategory(){

        List<String> category = wGoodsService.selectCategory();
        Map map = new HashMap();
        map.put("msg","商品创建成功");
        map.put("code",200);
        map.put("data",category);
        return map;
    }


    @ApiOperation("创建商品")
    @PostMapping("/creategoods")
    @Transactional
    public Map creategoods(HttpServletRequest request,@ModelAttribute @Validated GoodsVo goods){
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");//设置日期格式
        String newsNo =  LocalDateTime.now().format(fmt);

        @NotEmpty(message = "产品价格") String prPrice = goods.getPrPrice();
        BigDecimal price = BigDecimal.valueOf(Long.parseLong(prPrice));
        goods.setPrPric(price);

        //根据登录账号获取商铺id
        String sid=JwtUtil.getUsername(request.getAttribute("token1").toString());
        Integer shopId = wGoodsService.selectShopId(sid);
        goods.setShopId(shopId);
        goods.setPrId(newsNo);
        wGoodsService.creategoods(goods);

        //根据编号获取商品id
        Integer id = wGoodsService.selectByProId(newsNo);

        MultipartFile picture = goods.getPicture();

//        System.out.println(picture.getContentType().substring(6));// image/png
//        if (picture.isEmpty()) {
//            Map map = new HashMap();
//            map.put("msg","上传失败，请选择文件");
//            map.put("code",500);
//            return map;
//        }
//        COSClient cosClient = tencentUtil.tencentStart();
//        // bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
//        String bucketName = tencentUtil.getBucketName();
//
//        String uuid=null;
//
//        for(int i=0;i<10;i++){
//            uuid = UUID.randomUUID().toString().replaceAll("-", "");
//            System.out.println(uuid);
//        }
//        // 指定要上传到 COS 上对象键
//        // 对象键（Key）是对象在存储桶中的唯一标识。例如，在对象的访问域名 `bucket1-1250000000.cos.ap-beijing.myqcloud.com/mydemo.jpg` 中，对象键为 mydemo.jpg, 详情参考 [对象键](https://cloud.tencent.com/document/product/436/13324)
//        String key = tencentUtil.getQianzhui() + "/"+ tencentUtil.getQianzhui()+ "_" + uuid + "." + picture.getContentType().substring(6);
//        File localFile = null;
//        try {
//            //将 MultipartFile 类型 转为 File 类型
//            localFile = File.createTempFile("temp",null);
//            picture.transferTo(localFile);
//        }catch (IOException e){
//            Map map = new HashMap();
//            map.put("msg","上传出错，请联系管理员");
//            map.put("code",500);
//            return map;
//        }
//        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
//        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);


        String pic=null;
        //图片地址
        try {
            pic = ImageUpload.upload(picture);

        } catch (IOException e) {
            e.printStackTrace();
        }
        //存储图片
        wGoodsService.instrtPic(pic,id);
        System.out.println(goods);
        Map map = new HashMap();
        map.put("msg","商品创建成功");
        map.put("code",200);
        return map;
    }
}
